package com.sciology.xpathutility.contentassist;

import java.util.regex.Pattern;

public class CompletionTriggerExpression extends AbstractCompletionTrigger {

  public final static String INSTANCE_QNAME = "retrigger";  //$NON-NLS-1$
  public final static String REG_EXP_ATTRIBUTE_QNAME = "re"; //$NON-NLS-1$
  private final String regExp;
  private final Pattern pattern;
  private final String proposal;
  private final String plainProposal;
  
  /**
   * @param p_regExp
   * @param p_proposal
   */
  public CompletionTriggerExpression(String p_regExp, String p_proposal, String p_plainProposal) {
    this.regExp = p_regExp;
    this.proposal = p_proposal;
    this.pattern = Pattern.compile(this.regExp);
    this.plainProposal = p_plainProposal;
  }

  String getRegExp() {
    return this.regExp;
  }

  String getPlainProposal() {
    return this.plainProposal;
  }

  String getProposal() {
    return this.proposal;
  }

  public boolean isMatchFor(String text) {
    return this.pattern.matcher(text).matches();
  }

  public String getInsertString(String text) {
    return this.proposal;
  }
  
  public String getInsertString() {
    return this.getInsertString(this.text);
  }

  public int compareTo(AbstractCompletionTrigger p_other) {
    // Always prefer WordCompletions
    if (p_other instanceof CompletionTriggerWord) {
      return +1;
    }
    int thisLength = this.getInsertString().length();
    int otherLength = p_other.getInsertString().length(); 
    if (thisLength < otherLength) {
      return -1;
    } else {
      return +1;
    }
  }
}
